package com.haiyou.dc.message.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;


/**
 * HTTP 请求工具类 当前httpclient版本是4.5.2
 *
 * @author pc
 */
@Slf4j
public class HttpUtil {
    private static PoolingHttpClientConnectionManager connMgr;
    private static RequestConfig requestConfig;
    private static final int MAX_TIMEOUT = 15000;

    static {
        // 设置连接池
        connMgr = new PoolingHttpClientConnectionManager();
        // 设置连接池大小
        connMgr.setMaxTotal(100);
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());

        RequestConfig.Builder configBuilder = RequestConfig.custom();
        // 设置连接超时
        configBuilder.setConnectTimeout(MAX_TIMEOUT);
        // 设置读取超时
        configBuilder.setSocketTimeout(MAX_TIMEOUT);
        // 设置从连接池获取连接实例的超时
        configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
        // 在提交请求之前 测试连接是否可用
        configBuilder.setStaleConnectionCheckEnabled(true);
        requestConfig = configBuilder.build();
    }

    public static String doPostByRaw(String url, String json) {
        String content = null;
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            // json传递
            StringEntity jsonEntity = new StringEntity(json, Charset.forName("UTF-8"));
            post.setEntity(jsonEntity);
            post.setHeader("Content-type", "application/json");
            post.setHeader("token", "openfire");
            HttpResponse response = httpClient.execute(post);
            content = EntityUtils.toString(response.getEntity());
        } catch (UnsupportedEncodingException e) {
            log.error("doPostByRaw UnsupportedEncodingException,e=" + e.getMessage(), e);
        } catch (ClientProtocolException e) {
            log.error("doPostByRaw ClientProtocolException,e=" + e.getMessage(), e);
        } catch (ParseException e) {
            log.error("doPostByRaw ParseException,e=" + e.getMessage(), e);
        } catch (IOException e) {
            log.error("doPostByRaw IOException,e=" + e.getMessage(), e);
        }
        return content;
    }

}